<?php
declare (strict_types = 1);

namespace app\command;

use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use think\facade\Log;

class JinGoods extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('jingoods')
            ->setDescription('the jingoods command');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        //热卖商品榜
        $picking_pool_id = '3471903237135850815';
        $type = [0,373,374,375,376];
        $goods_type=2;
        $this->getHotGoods($picking_pool_id,$type,$goods_type);

        //精选推荐
        $picking_pool_id = '3472657720988036404';
        $type = [0,387,388,389];
        $goods_type=3;
        $this->getHotGoods($picking_pool_id,$type,$goods_type);

        // 指令输出
        $output->writeln('jingoods');
    }

    protected function getHotGoods($picking_pool_id,$type,$goods_type){
        $url = 'https://buyin.jinritemai.com/pc/picking/pool/promotions';
        $headers = [
            'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
            'Referer' => 'https://buyin.jinritemai.com',
            'Cookie'=>config('app.buyin_author.cookie')
        ];
        $param = [
            'picking_pool_id'=> $picking_pool_id,//'3471903237135850815',
            'filter_type'=> 10,
            'sort_type'=> 0,
            'cursor'=> 0,
            'session_id'=> '',
            'count'=> 60,
        ];
//        $cookies = config('app.buyin_author');
//        $cookieJar = CookieJar::fromArray($cookies, '.buyin.jinritemai.com');
        //$type = [0,373,374,375,376];

        foreach($type as $item){
            $param['gid'] = $item;
            $client = new Client();
            try {
                $response = $client->request('GET', $url, ['query'=>$param, 'headers'=>$headers]);

                $result = json_decode($response->getBody()->getContents(), true);

                if($result['code'] == 0){
                    if(isset($result['data']['promotions'])){
                        $time = date('Y-m-d H:i:s', time());
                        foreach($result['data']['promotions'] as $v){
                            $goodsExist = Db::name('activity_goods')->where(['product_id' => $v['product_id'],'goods_type'=>$goods_type])
                                ->field('id')->find();
                            $d = $this->getVolume($v['title']);
                            $ginfo = $this->getCategoryId($v['product_id']);
                            $shop_info = $this->getShop($v['shop_name']);
                            if($goodsExist){
                                $goods = [
                                    'product_promotion_id' => $v['promotion_id'],
                                    'product_id' => $v['product_id'],
                                    'product_name' => $v['title'],
                                    'product_price' => $v['price'],
                                    'product_img' => isset($v['cover']['url_list'][0]) ? $v['cover']['url_list'][0] : '',
                                    'product_stock' => 999,
                                    'shop_name' => $v['shop_name'],
                                    'shop_id' => $v['shop_id'],
                                    'dsr' => $v['exp_score'],
                                    'shop_phone' => isset($v['status_info']['shop_mobile']) ? $v['status_info']['shop_mobile'] : '',
                                    'commission_effect_start_time' => '2021-05-11',
                                    'commission_effect_end_time' => '2021-12-11',
                                    'commission_rate' => $v['cos_ratio'] > 0 ? (($v['cos_ratio'] / 100) + 0.1) : 0,
                                    'common_commission_rate' => $v['cos_ratio'] > 0 ? ($v['cos_ratio'] / 100) : 0,
                                    'service_rate' => 1,
                                    'promotion_url' => $v['detail_url'],
                                    'promotion_price' =>  $v['price'] > 0 ? ($v['price'] / 100) : 0,
                                    'promotion_stock' => 999,
                                    'gift_info' => '',
                                    'promotion_step' => '',
                                    'audit_status' => 1,
                                    'commission' => round((($v['cos_ratio'] > 0 ? (($v['cos_ratio'] / 100) + randFloat()) : 0)*$v['price'])/10000, 2),
                                    'volume' => $d ? ($d['day_order_count'] == '-' ? 0 : $d['day_order_count']) : 0,
                                    'order_count' => $d ? ($d['order_count'] == '-' ? 0 : $d['order_count']) : 0,
                                    'pv_count' => $d ? ($d['pv_count'] == '-' ? 0 :$d['pv_count']) : 0,
                                    'hot_promotion_wiseman' => $d ? ($d['total_author_count'] == '-' ? 0 : $d['total_author_count']) :0,
                                    'category_id' => $ginfo['first_cid'],
                                    'detail_delay_desc' => $ginfo['detail_delay_desc'],
                                    'description' => $ginfo['img_list'],
                                    'img_list' => $ginfo['img_list'],
                                    'shop_logo' => $ginfo['shop_logo'],
                                    'shop_tel' => $ginfo['shop_tel'],
                                    'shop_product' => $ginfo['shop_product'],
                                    'shop_service' => $ginfo['shop_service'],
                                    'shop_logistics' => $ginfo['shop_logistics'],
                                    'shop_ids' => $ginfo ? ((isset($ginfo['shop_id']) && $ginfo['shop_id'] != '') ? $ginfo['shop_id'] : '') : '',
                                    'status' => $ginfo ? ((isset($ginfo['product_id']) && $ginfo['product_id'] != '') ? 1 : 0) : 0,
                                    'goods_type' => $goods_type,//2,
                                    'buyin_activity_id' => 0,
                                    'apply_id' => generatie_aid(),
                                    'update_time' => $time
                                ];
                                Db::name('activity_goods')->where(['product_id' => $v['product_id'],'goods_type'=>$goods_type])->update($goods);
                            }else{
                                $goods = [
                                    'product_promotion_id' => $v['promotion_id'],
                                    'product_id' => $v['product_id'],
                                    'product_name' => $v['title'],
                                    'product_price' => $v['price'],
                                    'product_img' => isset($v['cover']['url_list'][0]) ? $v['cover']['url_list'][0] : '',
                                    'product_stock' => 999,
                                    'shop_name' => $v['shop_name'],
                                    'shop_id' => $v['shop_id'],
                                    'dsr' => $v['exp_score'],
                                    'shop_phone' => isset($v['status_info']['shop_mobile']) ? $v['status_info']['shop_mobile'] : '',
                                    'commission_effect_start_time' => '2021-05-11',
                                    'commission_effect_end_time' => '2021-12-11',
                                    'commission_rate' => $v['cos_ratio'] > 0 ? (($v['cos_ratio'] / 100) + randFloat()) : 0,
                                    'common_commission_rate' => $v['cos_ratio'] > 0 ? ($v['cos_ratio'] / 100) : 0,
                                    'service_rate' => 1,
                                    'promotion_url' => $v['detail_url'],
                                    'promotion_price' => $v['price'] > 0 ? ($v['price'] / 100) : 0,
                                    'promotion_stock' => 999,
                                    'gift_info' => '',
                                    'promotion_step' => '',
                                    'audit_status' => 1,
                                    'commission' => round((($v['cos_ratio'] > 0 ? (($v['cos_ratio'] / 100) + 0.1) : 0)*$v['price'])/10000, 2),
                                    'volume' => $d ? ($d['day_order_count'] == '-' ? 0 : $d['day_order_count']) : 0,
                                    'order_count' => $d ? ($d['order_count'] == '-' ? 0 : $d['order_count']) : 0,
                                    'pv_count' => $d ? ($d['pv_count'] == '-' ? 0 :$d['pv_count']) : 0,
                                    'hot_promotion_wiseman' => $d ? ($d['total_author_count'] == '-' ? 0 : $d['total_author_count']) :0,
                                    'category_id' => $ginfo['first_cid'],
                                    'detail_delay_desc' => $ginfo['detail_delay_desc'],
                                    'description' => $ginfo['img_list'],
                                    'img_list' => $ginfo['img_list'],
                                    'shop_logo' => $ginfo['shop_logo'],
                                    'shop_tel' => $ginfo['shop_tel'],
                                    'shop_product' => $ginfo['shop_product'],
                                    'shop_service' => $ginfo['shop_service'],
                                    'shop_logistics' => $ginfo['shop_logistics'],
                                    'shop_ids' => $ginfo ? ((isset($ginfo['shop_id']) && $ginfo['shop_id'] != '') ? $ginfo['shop_id'] : '') : '',
                                    'status' => $ginfo ? ((isset($ginfo['product_id']) && $ginfo['product_id'] != '') ? 1 : 0) : 0,
                                    'goods_type' => $goods_type,//2,
                                    'buyin_activity_id' => 0,
                                    'apply_id' => generatie_aid(),
                                    'create_time' => $time,
                                    'update_time' => $time
                                ];

                                Db::name('activity_goods')->insert($goods);
                            }

                            echo '.';
                        }
                        sleep(10);
                    }
                }else{
                    Log::info('调用接口失败' . $result['code']);
                    continue;
                }

            } catch (\Exception $e) {
                Log::info('调用接口失败' . $e->getMessage());
            }
        }

    }

    protected function getVolume($product_name){

        $url = 'https://api-service.chanmama.com/v1/product/search';
        $data = '{"keyword":"'.$product_name.'","keyword_type":"","page":1,"price":"","size":50,"filter_coupon":0,"is_aweme_goods":0,"has_live":0,"has_video":0,"tb_max_commission_rate":"","day_pv_count":"","day_order_count":"","big_category":"","first_category":"","second_category":"","platform":"","sort":"auto","order_by":"desc"}';
        $data = json_decode($data, true);
        $headers = [
            'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
            'Referer' => 'https://www.chanmama.com'
        ];
        $client = new Client();
        try {
            $response = $client->request('post', $url, ['json'=>$data, 'timeout'=>120, 'headers'=>$headers]);
            $result = json_decode($response->getBody()->getContents(), true);
            if(isset($result['errCode']) && ($result['errCode'] == 0)){

                if(isset($result['data']['list'][0])){
                    return $result['data']['list'][0];
                }else{
                    return [];
                }
            }else{
                return [];
            }
        }catch (\Exception $e){
            Log::info('调用接口失败' . $e->getMessage());
            exit;
        }

    }

    protected function getShop($shop_name){
        $url = 'https://api-service.chanmama.com/v1/shop/search';
        $data = [
            'page'=>1,
            'big_category'=>'',
            'first_category'=>'',
            'keyword'=>$shop_name,
            'sort'=>'volume',
            'orderby'=>'desc',
            'size'=>50,
            'has_aweme'=>0,
            'has_live'=>0,
            'avg_price'=>'',
            'avg_amount'=>'',
        ];
        $client = new Client();
        $headers = [
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
            'Referer' => $url
        ];

        try {
            $response = $client->request('GET', $url, ['query'=>$data, 'timeout'=>120, 'headers'=>$headers]);
            $result = json_decode($response->getBody()->getContents(), true);
//            echo '<pre>';print_r($result);exit;
            if($result['data']){
                $index = 0;
                if($result['data']['list']){

                    foreach($result['data']['list'] as $k=>$v){
                        if($v['shop_name'] == $shop_name){
                            $index = $k;
                            break;
                        }
                    }

                    return $result['data']['list'][$index];
                }else{
                    return [];
                }
            }else{
                return [];
            }
        }catch (\Exception $e){
            Log::info('调用接口失败' . $e->getMessage());
            exit;
        }
    }

    protected function getCategoryId($productc_id){
        $client = new Client();
        $url = 'https://ec.snssdk.com/product/fxgajaxstaticitem';
        $payload = [
            'b_type_new' => 0,
            'device_id' => 0,
            'id' => $productc_id,
            'preview' => 0
        ];
        $headers = ['user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36'];
        try {
            $response = $client->request('GET', $url, ['query' => $payload, 'timeout' => 120, 'headers'=>$headers]);
            $result = json_decode($response->getBody()->getContents(), true);
            $data = [
                'first_cid'=>0,
                'detail_delay_desc'=>'',//发货时间
                'description'=>'',//商品描述图片
                'img_list'=>'',//商品轮播图
                'shop_logo'=>'',//商家头像
                'shop_tel'=>'',//商家联系电话
                'shop_product'=>'',//商家体验
                'shop_service'=>'',//商家服务
                'shop_logistics'=>'',//物流体验
                'product_id'=>'',//物流体验
                'shop_id'=>'',
            ];
            if(isset($result['data']) && $result['data']){
                if(isset($result['data']['extra']['category_detail']['first_cid'])){
                    $data['first_cid'] = $result['data']['extra']['category_detail']['first_cid'];
                }

                if(isset($result['data']['detail_delay_desc'])){
                    $data['detail_delay_desc'] = $result['data']['detail_delay_desc'];
                }

                if(isset($result['data']['description'])){
                    $data['description'] = $result['data']['description'];
                }

                if(isset($result['data']['img_list'])){
                    $data['img_list'] = $result['data']['img_list'] ? json_encode($result['data']['img_list']) :'';
                }

                if(isset($result['data']['shop_logo'])){
                    $data['shop_logo'] = $result['data']['shop_logo'];
                }

                if(isset($result['data']['mobile'])){
                    $data['shop_tel'] = $result['data']['mobile'];
                }

                if(isset($result['data']['credit_score'])){
                    $data['shop_product'] = $result['data']['credit_score']['product'];
                    $data['shop_service'] = $result['data']['credit_score']['shop'];
                    $data['shop_logistics'] = $result['data']['credit_score']['logistics'];
                }

                if(isset($result['data']['product_id'])){
                    $data['product_id'] = $result['data']['product_id'];
                }

                if(isset($result['data']['shop_id'])){
                    $data['shop_id'] = $result['data']['shop_id'];
                }

            }

            return $data;
        } catch (\Exception $e) {
            Log::info('调用接口失败' . $e->getMessage());
            exit;
        }
    }
}
